package deng.ejbtx.jboss;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;

import org.apache.log4j.Logger;
import org.jboss.annotation.ejb.Management;
import org.jboss.annotation.ejb.Service;

import deng.ejbtx.ejb.FilePollerTimerBean;
import deng.pojo.SmartProperties;

@Management(AppService.class)
@Service
@Local
public class AppServiceStarter implements AppService {

	public final static String SERVICE_CONFIG_KEY = "deng.ejbtx.jboss.config";
	public final static String DEFAULT_SERVICE_CONFIG = "${jboss.server.config.url}appServiceConfig.properties";
	
	private static Logger logger = Logger.getLogger(AppServiceStarter.class);
	
	@Resource
	private String configUrlName;
	
	private SmartProperties config = new SmartProperties();
	
	@EJB
	private FilePollerTimerBean filePollerBean;
	
	private int attribute; // For @Management
	
	@Override
	public SmartProperties getConfig() {
		return config;
	}
	
	@Override
	public void create() throws Exception {
		if (configUrlName == null) {
			configUrlName = System.getProperty(SERVICE_CONFIG_KEY, DEFAULT_SERVICE_CONFIG);
		}
		logger.info("Loading config " + configUrlName);
		config.loadURL(configUrlName);
		logger.info("AppStarter service created.");
	}
	@Override
	public void start() throws Exception {	
		int delay = config.getInt("filePollerDelay");
		int period = config.getInt("filePollerPeriod");
		String filePollerDir = config.getString("filePollerDir");
		String filePollerScript = config.getString("filePollerScript");
		logger.info("Creating filePollerBean EJB timer: " +
				"\n  delay=" + delay + ", period=" + period + 
				"\n  filePollerDir=" + filePollerDir + 
				"\n  filePollerScript=" + filePollerScript);
		filePollerBean.createTimer(delay, period,  filePollerDir, filePollerScript);
		logger.info("AppStarter service started.");
	}
	@Override
	public void stop() {
		logger.info("Stopping filePollerBean EJB timer");
		filePollerBean.stopTimer();
		logger.info("AppStarter service stopped.");
	}
	@Override
	public void destroy() {
		logger.info("AppStarter service destroyed.");
	}
	@Override
	public int getAttribute() {
		return attribute;	
	}
	@Override
	public void setAttribute(int attribute) {
		this.attribute = attribute;
	}
}
